import { ref, Ref, watch, defineComponent } from 'vue';
import {
  getDataPickerProps,
  getEditorEmits,
  useNamespace,
} from '@ibiz-template/vue3-util';
import { isNil } from 'ramda';
import './ibiz-picker-dropdown.scss';
import { PickerEditorController } from '../picker-editor.controller';

export const IBizPickerDropDown = defineComponent({
  name: 'IBizPickerDropDown',
  props: getDataPickerProps<PickerEditorController>(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('picker-dropdown');

    const c = props.controller;

    // 当前值
    const curValue: Ref<Array<string> | string | null> = ref('');

    // 实体数据集
    const items: Ref<IData[]> = ref([]);

    // 是否能请求
    const shouldLoad = ref(false);

    watch(
      () => props.value,
      newVal => {
        if (newVal || newVal === null) {
          curValue.value = newVal;
          const value = props.data[c.valueItem];
          const index = items.value.findIndex((item: IData) =>
            Object.is(item[c.keyName], value),
          );
          if (index !== -1) {
            return;
          }
          // items里匹配不到当前值项值时，生成自身的选项
          items.value = [];
          if (!isNil(newVal) && !isNil(value)) {
            items.value.push({ [c.textName]: newVal, [c.keyName]: value });
          }
        }
      },
      { immediate: true },
    );

    // 获取关联数据项值
    const refValue = ref('');

    watch(
      () => props.data[c.valueItem],
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          refValue.value = newVal;
          // 如果值项被清空了，主文本也需清空
          if (newVal === null) {
            emit('change', null);
          }
        }
      },
      { immediate: true, deep: true },
    );

    // 加载中
    const loading: Ref<boolean> = ref(false);

    // 往外抛值
    const onACSelect = async (item: IData) => {
      // 处理回填数据
      const dataItems = await c.calcFillDataItems(item);
      if (dataItems.length) {
        dataItems.forEach(dataItem => {
          emit('change', dataItem.value, dataItem.id);
        });
      }

      // 处理值项和本身的值
      if (c.valueItem) {
        emit('change', item[c.keyName], c.valueItem);
      }
      emit('change', item[c.textName]);
    };

    // 值变更
    const onSelect = (select: string | Array<string>) => {
      const index = items.value.findIndex(item =>
        Object.is(item[c.keyName], select),
      );
      if (index >= 0) {
        onACSelect(items.value[index]);
      }
      shouldLoad.value = false;
    };

    // 在搜索中时，再次触发搜索记录搜索值，等待上次搜索触发完成后再次搜索
    let waitQuery: string | null = null;

    // 搜索
    const onSearch = async (query: string) => {
      // 失焦那次不用发请求
      if (!shouldLoad.value) {
        return;
      }
      if (c.model.appDataEntityId && loading.value === false) {
        loading.value = true;
        try {
          let trimQuery = '';
          if (query !== props.value) {
            trimQuery = query.trim();
          }
          const res = await c.getServiceData(trimQuery, props.data!);
          if (res) {
            items.value = res.data as IData[];
          }
        } finally {
          loading.value = false;
          if (waitQuery != null) {
            const selfQuery = waitQuery;
            waitQuery = null;
            await onSearch(selfQuery);
          }
        }
      } else {
        waitQuery = query;
      }
    };

    // 下拉打开
    const onOpenChange = (isOpen: boolean) => {
      if (isOpen) {
        items.value = [];
        onSearch('');
      }
    };

    // 清除
    const onClear = () => {
      // 清空回填数据
      const dataItems = c.dataItems;
      if (dataItems?.length) {
        dataItems.forEach(dataItem => {
          emit('change', null, dataItem.id);
        });
      }
      if (c.valueItem) {
        emit('change', null, c.valueItem);
      }
      emit('change', null);
    };

    // 聚焦
    const onFocus = () => {
      shouldLoad.value = true;
      emit('focus');
    };

    // 失焦
    const onBlur = () => {
      shouldLoad.value = false;
      emit('blur');
    };

    // 点击
    const onClick = () => {
      shouldLoad.value = true;
    };

    return {
      ns,
      c,
      refValue,
      loading,
      items,
      onOpenChange,
      onClear,
      onSelect,
      onSearch,
      onFocus,
      onBlur,
      onClick,
    };
  },
  render() {
    if (this.readonly) {
      return (
        <div class={(this.ns.b(), this.ns.m('readonly'))}>{this.value}</div>
      );
    }
    return (
      <div class={[this.ns.b(), this.disabled ? this.ns.m('disabled') : '']}>
        {this.readonly ? (
          this.value
        ) : (
          <el-select
            v-model={this.refValue}
            filterable
            remote
            clearable
            loading={this.loading}
            placeholder={this.c.placeHolder ? this.c.placeHolder : ' '}
            remote-method={this.onSearch}
            onVisibleChange={this.onOpenChange}
            onChange={this.onSelect}
            onClear={this.onClear}
            disabled={this.disabled}
            onFocus={this.onFocus}
            onBlur={this.onBlur}
            onClick={this.onClick}
          >
            {this.items.map((item, index) => {
              return (
                <el-option
                  value={item[this.c.keyName]}
                  key={index}
                  label={item[this.c.textName]}
                ></el-option>
              );
            })}
          </el-select>
        )}
      </div>
    );
  },
});
